package Servlet;

import dao.MyConnection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class changePlaceStatusServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        int type = Integer.parseInt(request.getParameter("opType"));
        String placeNumber = request.getParameter("placeNumber");
        MyConnection myCon = new MyConnection();
        myCon.getConnection();
        int res = -1;
        try {
            if (type == 1) {
                PreparedStatement ps = myCon.connection.prepareStatement("update place set placeStatus=1 where placeNumber=?");
                ps.setString(1, placeNumber);
                res = ps.executeUpdate();
                ps.close();
            } else if (type == 0) {
                PreparedStatement ps = myCon.connection.prepareStatement(
                        "update place set placeStatus=0 where placeNumber=? and (select count(*) from appointment where AppointmentTime>current_time() and placeNumber=?)=0;");
                ps.setString(1, placeNumber);
                ps.setString(2, placeNumber);
                res = ps.executeUpdate();
                ps.close();
            } else {
                PreparedStatement ps = myCon.connection.prepareStatement(
                        "delete from place where placeNumber=? and (select count(*) from appointment where AppointmentTime>current_time() and placeNumber=?)=0;");
                ps.setString(1, placeNumber);
                ps.setString(2, placeNumber);
                res = ps.executeUpdate();
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            myCon.closeConnection();
        }
        out.print(res);
    }
}
